package com.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.enums.ServiceExceptionEnum;
import com.util.CommonFunctionUtil;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;
import java.util.Objects;

@AllArgsConstructor
@Data
public class ApiResponse<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = -3613582179094754781L;
    private String errorCode;
    private String msg;
    private T returnData;

    public ApiResponse(){}

    public ApiResponse(String errCode, String msg) {
        this.errorCode = errCode;
        this.msg = "【" +errCode + "】:"+msg;
        this.returnData = null;
    }

    public ApiResponse(ServiceExceptionEnum serviceExceptionEnum) {
        this.errorCode = serviceExceptionEnum.getCode();
        if(isSuccess()){
            this.msg = serviceExceptionEnum.getMsg();
        }else{
            this.msg = CommonFunctionUtil.formatServiceErrorMsg(serviceExceptionEnum);
        }
        this.returnData = null;
    }

    public ApiResponse(ServiceExceptionEnum serviceError, T data) {
        this(serviceError);
        this.returnData = data;
    }

    public static <T> ApiResponse<T> error() {
        return new ApiResponse<>(ServiceExceptionEnum.UNKNOWN_FAILURE);
    }

    @JsonIgnore
    public Boolean isSuccess(){
        return Objects.equals(this.errorCode, ServiceExceptionEnum.OK.getCode());
    }


    public static <T> ApiResponse<T> ok(T data) {
        return new ApiResponse<>(ServiceExceptionEnum.OK,data);
    }

    public static <T> ApiResponse<T> error(ServiceExceptionEnum serviceError) {
        return new ApiResponse<>(serviceError);
    }

    public static <T> ApiResponse<T> error(ServiceExceptionEnum serviceError, T data) {
        return new ApiResponse<>(serviceError,data);
    }

    public static <T> ApiResponse<T> error(String errCode, String errorMsg) {
        return new ApiResponse<>(errCode,errorMsg);
    }

    public static <T> ApiResponse<T> error(String errCode, String errorMsg, T data) {
        return new ApiResponse<>(errCode,errorMsg,data);
    }
}
